#include <opencv2/opencv.hpp>
#include<iostream>
#include "face.h"
using namespace std;
using namespace cv;
using namespace aip;
vector<Rect> faces;
vector<uchar> face_state;
time_t t;
int main()
{
    Mat adjust1,frame,adjust2,adjust3;
    CascadeClassifier face_detect("/usr/share/opencv4/haarcascades/haarcascade_frontalface_alt.xml");
    VideoCapture cap(0);
    string appid = "118474182";

    string api_key = "3jeyiTLRacUq3JHnGXNOdXHx";

    string secret_key = "S8aX5iWEYgKpNtMpPfNeYdOxmXEEd0jS";

    string base64_img;

    Face client(appid, api_key, secret_key);
    Json::Value result;
    int record_time = 0;//时间cnt
    int during_time = 1000;
    string Text_save = "";
    while(1)
    {
        cap>>frame;
        cvtColor(frame,adjust1,COLOR_BGR2GRAY);
        //均衡处理
        equalizeHist(adjust1,adjust2);
        face_detect.detectMultiScale(adjust2,faces,1.1,3,0,Size(30,30));
        if(faces.size())
        {
            rectangle(adjust2,faces[0],Scalar(255,0,0));
            adjust3 = adjust2(faces[0]);
            imencode(".jpg",adjust3,face_state);
            base64_img = base64_encode((char *)face_state.data(), face_state.size());
            result = client.face_search_v3(base64_img, "BASE64","1",Json::Value::null);//一定要注意这里"1"指的是group_id
            //cout<<result<<"\n";
            if(!result["result"].isNull())
            {
                if(result["result"]["user_list"][0]["score"].asInt() > 75)
                {
                    cout << result["result"]["user_list"][0]["user_id"]<<"\n";
                    t = time(NULL);
                    // Text_save += ctime(&t);
                    // record_time = during_time;
                    cout<<ctime(&t)<<"\n";//转换成具体时间
                    char time1[30];

                    Text_save = result["result"]["user_list"][0]["user_id"].asString() + " - " + result["result"]["user_list"][0]["score"].asString() + " - " + string(time1);
                    record_time = during_time; 
                }
            }
        }
        if(record_time > 0)
        {
            putText(adjust2,Text_save,Point(0,55),FONT_HERSHEY_SIMPLEX,1.1,Scalar(0,0,0),5);
            putText(adjust2,ctime(&t),Point(0,100),FONT_HERSHEY_SIMPLEX,1.1,Scalar(0,0,0),5);
            putText(adjust2,"finish",Point(0,150),FONT_HERSHEY_TRIPLEX,1.1,Scalar(0,0,0),5);
            record_time --;

        }   

        imshow("video",adjust2);
        cv::waitKey(40);
    }
    return 0;
}